﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Text.RegularExpressions;

using System.Data.Linq;
using HtmlAgilityPack;
using System.Text;
using System.Windows.Controls.Primitives;
using System.Collections.ObjectModel;
using OnlineVideos;

using Common.Library;
using System.Data.Linq.SqlClient;
using System.Windows.Media.Imaging;

namespace webslice
{
    public partial class BrowserPage : PhoneApplicationPage
    {
        public string mode = string.Empty;
        public string BasicUri = string.Empty;
        public string Navigatinguri = string.Empty;
        public string SelectedText = string.Empty;
        public List<string> NavigationHistory = new List<string>();
        bool PageLoad = false;
        bool NavigatingBack = false;
        public BrowserPage()
        {
            InitializeComponent();
            Loaded += new RoutedEventHandler(BrowserPage_Loaded);
           
        }

        void BrowserPage_Loaded(object sender, RoutedEventArgs e)
        {
            webBrowser1.Navigate(new Uri(Navigatinguri, UriKind.RelativeOrAbsolute), null, "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Trident/5.0)");
            webBrowser1.Navigated += new EventHandler<System.Windows.Navigation.NavigationEventArgs>(webBrowser1_Navigated);
            this.IsEnabled = false;
            Constants.NavigatedToBrowser = true;
        }
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            Navigatinguri = NavigationContext.QueryString["url"];
            mode = NavigationContext.QueryString["mode"];
        }
        
        void webBrowser1_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            try
            {
               
                BasicUri = e.Uri.Host.ToString();
                PageLoad = false;
                if (BasicUri.Contains("www"))
                    Constants.BasicUri = BasicUri.Substring((BasicUri.IndexOf("www") + 4), BasicUri.Substring(BasicUri.IndexOf("www") + 4).IndexOf('.'));
                else
                    Constants.BasicUri = BasicUri.Substring(0, BasicUri.IndexOf('.'));
                App.webinfo.PivotImage = "http://www.google.com/s2/favicons?domain=" + BasicUri;
                if (mode == "numeric")
                {

                    webBrowser1.InvokeScript("eval", "function clickhandler(e){e.cancelBubble = true;var targetElement = e.target;var  dataValue= document.selection.createRange().htmlText.toString().replace(/\\n/g, '').replace(/<br>/g, '<br />').replace(/\\r/g, '').replace(/\\t/g, ''); var htmlText, leftString, rightString;var leftPos, rightPos;do{ htmlText = targetElement.outerHTML.replace(/\\n/g, '').replace(/<br>/g, '<br />').replace(/\\r/g, '').replace(/\\t/g, '');leftPos = htmlText.indexOf(dataValue);  rightPos = leftPos + dataValue.length;leftString = htmlText.substring(0, leftPos).replace(/\\n/g, '').replace(/<br>/g, '<br />').replace(/\\r/g, '').replace(/\\t/g, '');var leftString1 = leftString.replace(/\\$/g, '').replace(/\\^/g, '').replace(/\\./g, '').replace(/\\|/g, '').replace(/\\?/g, '').replace(/\\*/g, '').replace(/\\+/g, '').replace(/\\(/g, '').replace(/\\)/g, '').replace(/\\{/g, '').replace(/\\}/g, '').replace(/\\]/g, '').replace(/\\[/g, '').replace(/\\</g, '').replace(/\\>/g, '').replace(/\\&/g, '').replace(/\\-/g, '');rightString = htmlText.substring(rightPos, htmlText.length).replace(/\\n/g, '').replace(/<br>/g, '<br />').replace(/\\r/g, '').replace(/\\t/g, '') ;var fullhtml=document.documentElement.outerHTML.replace(/\\n/g, '').replace(/<br>/g, '<br />').replace(/\\r/g, '').replace(/\\t/g, '').replace(/\\$/g, '').replace(/\\^/g, '').replace(/\\./g, '').replace(/\\|/g, '').replace(/\\?/g, '').replace(/\\*/g, '').replace(/\\+/g, '').replace(/\\(/g, '').replace(/\\)/g, '').replace(/\\{/g, '').replace(/\\}/g, '').replace(/\\]/g, '').replace(/\\[/g, '').replace(/\\</g, '').replace(/\\>/g, '').replace(/\\&/g, '').replace(/\\-/g, '');var matches = fullhtml.match(new RegExp(leftString1,\"gi\"));targetElement = targetElement.parentNode;}while(matches.length > 1 && targetElement != null);var returnString =  leftString + \"??\" +dataValue + \"??\" +rightString;window.external.notify(returnString);}");
                    webBrowser1.InvokeScript("eval", "this.Add_eventHandler=function(e) {for (var i = 0; i < document.all.length; i++) {document.all[i].addEventListener(\"copy\", clickhandler);}}");
                    webBrowser1.InvokeScript("Add_eventHandler");
                    
                }
                else
                {
                    webBrowser1.InvokeScript("eval", "function clickhandler(e){e.cancelBubble = true;var targetElement = e.target;var  dataValue= targetElement.innerHTML.replace(/\\n/g, '').replace(/<br>/g, '<br />').replace(/\\r/g, '').replace(/\\t/g, ''); var htmlText, leftString, rightString;var leftPos, rightPos;do{ htmlText = targetElement.outerHTML.replace(/\\n/g, '').replace(/<br>/g, '<br />').replace(/\\r/g, '').replace(/\\t/g, '');leftPos = htmlText.indexOf(dataValue);  rightPos = leftPos + dataValue.length;leftString = htmlText.substring(0, leftPos).replace(/\\n/g, '').replace(/<br>/g, '<br />').replace(/\\r/g, '').replace(/\\t/g, '');var leftString1 = leftString.replace(/\\$/g, '').replace(/\\^/g, '').replace(/\\./g, '').replace(/\\|/g, '').replace(/\\?/g, '').replace(/\\*/g, '').replace(/\\+/g, '').replace(/\\(/g, '').replace(/\\)/g, '').replace(/\\{/g, '').replace(/\\}/g, '').replace(/\\]/g, '').replace(/\\[/g, '').replace(/\\</g, '').replace(/\\>/g, '').replace(/\\&/g, '').replace(/\\-/g, '');rightString = htmlText.substring(rightPos, htmlText.length).replace(/\\n/g, '').replace(/<br>/g, '<br />').replace(/\\r/g, '').replace(/\\t/g, ''); var fullhtml=document.documentElement.outerHTML.replace(/\\n/g, '').replace(/<br>/g, '<br />').replace(/\\r/g, '').replace(/\\t/g, '').replace(/\\$/g, '').replace(/\\^/g, '').replace(/\\./g, '').replace(/\\|/g, '').replace(/\\?/g, '').replace(/\\*/g, '').replace(/\\+/g, '').replace(/\\(/g, '').replace(/\\)/g, '').replace(/\\{/g, '').replace(/\\}/g, '').replace(/\\]/g, '').replace(/\\[/g, '').replace(/\\</g, '').replace(/\\>/g, '').replace(/\\&/g, '').replace(/\\-/g, '');var matches = fullhtml.match(new RegExp(leftString1,\"gi\"));targetElement = targetElement.parentNode;}while(matches.length > 1 && targetElement != null);var returnString =  leftString + \"??\" +dataValue + \"??\" +rightString;window.external.notify(returnString);}");
                    webBrowser1.InvokeScript("eval", "this.Add_eventHandler=function(e) {for (var i = 0; i < document.all.length; i++) {document.all[i].addEventListener(\"copy\", clickhandler);}}");
                    webBrowser1.InvokeScript("Add_eventHandler");
                }

              
                this.IsEnabled = true;
            }
            catch (Exception ex)
            {
            }
        }

        void webBrowser1_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            NavigationHistory.Add(e.Uri.ToString());
            
          
        }

        private void webBrowser1_ScriptNotify(object sender, NotifyEventArgs e)
        {
            try
            {
                if (e.Value != null)
                {
                    if (SelectedText != e.Value.ToString())
                    {
                        SelectedText = e.Value.ToString();
                        bool valid = default(bool);
                        string select = SelectedText.Split(new string[] { "??" }, StringSplitOptions.None)[1].ToString().Replace("<br>", "<br />").Replace("\n", "").Replace("\t", "").Replace("\r", "");
                        try
                        {
                            double pp = Convert.ToDouble(select);
                            valid = true;
                        }
                        catch (Exception ex)
                        {
                            valid = false;
                        }
                        if ((valid == true && mode == "numeric") || (valid == false && mode == "string"))
                        {
                            MessageBoxResult result = default(MessageBoxResult);

                            result = MessageBox.Show("you have selected " + SelectedText.Split(new string[] { "??" }, StringSplitOptions.None)[1].ToString().Replace("<br>", "<br />").Replace("\t", "").Replace("\n", "").Replace("\r", ""), "", MessageBoxButton.OKCancel);
                            if (result == MessageBoxResult.OK)
                            {
                                App.webinfotable.SelectedText = SelectedText.Split(new string[] { "??" }, StringSplitOptions.None)[1].ToString().Replace("<br>", "<br />").Replace("\n", "").Replace("\r", "").Replace("\t", "");
                                App.webinfotable.BeforeText = SelectedText.Split(new string[] { "??" }, StringSplitOptions.None)[0].ToString().Replace("<br>", "<br />").Replace("\n", "").Replace("\r", "").Replace("\t", "");
                                App.webinfotable.AfterText = SelectedText.Split(new string[] { "??" }, StringSplitOptions.None)[2].ToString().Replace("<br>", "<br />").Replace("\n", "").Replace("\r", "").Replace("\t", "");
                                WebClient wb = new WebClient();
                                wb.DownloadStringAsync(new Uri(App.webinfotable.NavigationUri, UriKind.Absolute));
                                wb.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wb_DownloadStringCompleted);
                            }
                        }
                        else
                        {
                            MessageBoxResult result = default(MessageBoxResult);
                            result = MessageBox.Show("selected Text is not " + mode, "", MessageBoxButton.OK);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }
           
        }

        public ObservableCollection<string> GetImages(string input)
        {
            ObservableCollection<string> list = new ObservableCollection<string>();
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(input);
           
            foreach (HtmlNode node in doc.DocumentNode.SelectNodes(" //img"))
            {
                if (node.OuterHtml.Contains("src") || node.OuterHtml.Contains("data-src") || node.OuterHtml.Contains("dfr-src") || node.OuterHtml.Contains("deferredsrc"))
                {
                    if (((node.Attributes["src"] == null) ? (node.Attributes["data-src"] == null) ? (node.Attributes["dfr-src"] == null) ? (node.Attributes["data-src-onload"] == null) ? node.Attributes["deferredsrc"] : node.Attributes["data-src-onload"] : node.Attributes["dfr-src"] : node.Attributes["data-src"] : node.Attributes["src"]).Value.StartsWith("http"))
                    {



                        list.Add(((node.Attributes["src"] == null) ? (node.Attributes["data-src"] == null) ? (node.Attributes["dfr-src"] == null) ? (node.Attributes["data-src-onload"] == null) ? node.Attributes["deferredsrc"] : node.Attributes["data-src-onload"] : node.Attributes["dfr-src"] : node.Attributes["data-src"] : node.Attributes["src"]).Value);
                    }
                    else
                    {

                        list.Add(BasicUri + ((node.Attributes["src"] == null) ? (node.Attributes["data-src"] == null) ? (node.Attributes["dfr-src"] == null) ? (node.Attributes["data-src-onload"] == null) ? node.Attributes["deferredsrc"] : node.Attributes["data-src-onload"] : node.Attributes["dfr-src"] : node.Attributes["data-src"] : node.Attributes["src"]).Value);
                    }
                }
            }
            return list;
        }

      
        void wb_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Result != null)
            {
              
                string PageHtml = e.Result.ToString();
                Constants.ImageUrls.Clear();
                Constants.ImageUrls = GetImages(PageHtml);
                NavigationService.GoBack();
               
            }
        }

      
        private void webBrowser1_Navigating(object sender, NavigatingEventArgs e)
        {
            if (NavigatingBack == false)
            {
                App.webinfotable.NavigationUri = e.Uri.ToString();
                if (PageLoad == false)
                {
                    e.Cancel = true;
                    webBrowser1.Navigate(new Uri(e.Uri.ToString(), UriKind.RelativeOrAbsolute), null, "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Trident/5.0)");
                }
                this.IsEnabled = false;
                PageLoad = true;
            }
            else
            {
                NavigatingBack = false;
            }
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            if (NavigationHistory.Count > 0)
            {
                e.Cancel = true;
                NavigateBack();
            }
            else
                base.OnBackKeyPress(e);
        }

        public void NavigateBack()
        {
            NavigatingBack = true;
            webBrowser1.InvokeScript("eval", "history.go(-1)");
            NavigationHistory.RemoveAt(NavigationHistory.Count - 1);
        }

        private void Image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            NavigationService.GoBack();
        }
    }
}